package cn.com.nes.common.util;

import cn.com.nes.common.wx.MyX509TrustManager;
import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.DataRes;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.UserInfo;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import io.jsonwebtoken.Claims;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.ModelMap;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DBUtils {
	private Connection conn = null;

	public DBUtils(Connection conn) {
		this.conn = conn;
	}

	public static boolean isEmpty(String str) {
		if(str==null||str.trim().equals("")){
			return true ;
		}
		return false ;
	}
	
	
	public static void printLog(String log) {
		StringBuffer sb = new StringBuffer();
		sb.append(
				new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS")
						.format(new Date())).append(": ").append(log);
		System.out.println(sb.toString());
		// LogToFile(sb.toString());

	}

	public static final byte[] input2byte(InputStream inStream)
			throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}

	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String convertString(String gbk) {
		String utf8 = "";
		try {
			utf8 = new String(gbk2utf8(gbk), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			utf8 = gbk;
		}
		return utf8;
	}

	public static byte[] gbk2utf8(String chenese) {
		char c[] = chenese.toCharArray();
		byte[] fullByte = new byte[3 * c.length];
		for (int i = 0; i < c.length; i++) {
			int m = (int) c[i];
			String word = Integer.toBinaryString(m);

			StringBuffer sb = new StringBuffer();
			int len = 16 - word.length();
			for (int j = 0; j < len; j++) {
				sb.append("0");
			}
			sb.append(word);
			sb.insert(0, "1110");
			sb.insert(8, "10");
			sb.insert(16, "10");

			String s1 = sb.substring(0, 8);
			String s2 = sb.substring(8, 16);
			String s3 = sb.substring(16);

			byte b0 = Integer.valueOf(s1, 2).byteValue();
			byte b1 = Integer.valueOf(s2, 2).byteValue();
			byte b2 = Integer.valueOf(s3, 2).byteValue();
			byte[] bf = new byte[3];
			bf[0] = b0;
			fullByte[i * 3] = bf[0];
			bf[1] = b1;
			fullByte[i * 3 + 1] = bf[1];
			bf[2] = b2;
			fullByte[i * 3 + 2] = bf[2];

		}
		return fullByte;
	}

	public static String getDate(int offset) {
		SimpleDateFormat formatter = Globals.DATE_FORMAT_SHORT;
		Date myDate = new Date();
		long myTime = (myDate.getTime() / 1000) + 60 * 60 * 24 * offset;
		myDate.setTime(myTime * 1000);
		String mDate = formatter.format(myDate);
		return mDate;
	}
	
	public static String getCurTime() {
		SimpleDateFormat formatter = Globals.DATE_FORMAT_LONG;
		Date myDate = new Date();
		String mDate = formatter.format(myDate);
		return mDate;
	}

	public static Date StrToDate(String str) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = format.parse(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date;
	}

	public static String getDate(Date myDate, int offset) {
		SimpleDateFormat formatter = Globals.DATE_FORMAT_SHORT;
		long myTime = (myDate.getTime() / 1000) + 60 * 60 * 24 * offset;
		myDate.setTime(myTime * 1000);
		String mDate = formatter.format(myDate);
		return mDate;
	}

	public static String getCurYear() {
		// SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		// Date myDate = new Date();
		// String mDate = formatter.format(myDate);
		Calendar cal = new GregorianCalendar();
		int year = cal.get(Calendar.YEAR) - 1;
		return String.valueOf(year);
	}

	public static boolean isNumber(String str) {
		if (str == null || str.equals("")) {
			return false;
		}
		java.util.regex.Pattern pattern = java.util.regex.Pattern
				.compile("^(-(([0-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,16})?)|((([0-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,16})?)$");
//				.compile("^(([0-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,16})?$"); // 判断小数点后一位的数字的正则表达式
		java.util.regex.Matcher match = pattern.matcher(str);
		if (match.matches() == false) {
			return false;
		} else {
			return true;
		}
	}

	public static long getDaySub(String beginDateStr, String endDateStr) {
		long day = 0;
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
				"yyyy-MM-dd");
		java.util.Date beginDate;
		java.util.Date endDate;
		try {
			beginDate = format.parse(beginDateStr);
			endDate = format.parse(endDateStr);
			day = (endDate.getTime() - beginDate.getTime())
					/ (24 * 60 * 60 * 1000);
			// System.out.println("相隔的天数="+day);
		} catch (ParseException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
		return day;
	}

	public static String createRandom(boolean numberFlag, int length) {
		String retStr = "";
		String strTable = numberFlag ? "1234567890"
				: "1234567890abcdefghijkmnpqrstuvwxyz";
		int len = strTable.length();
		boolean bDone = true;
		do {
			retStr = "";
			int count = 0;
			for (int i = 0; i < length; i++) {
				double dblR = Math.random() * len;
				int intR = (int) Math.floor(dblR);
				char c = strTable.charAt(intR);
				if (('0' <= c) && (c <= '9')) {
					count++;
				}
				retStr += strTable.charAt(intR);
			}
			if (count >= 2) {
				bDone = false;
			}
		} while (bDone);
		return retStr;
	}

	public static String getNullData(String data) {
		if (data == null || data.equals("") || data.equals("null")) {
			data = null;
		}
		return data;
	}

	public static String getNull(String data) {
		if (data == null || data.equals("null")) {
			data = "";
		}
		return data;
	}

	public static int isNumber1(String s) {

		String regex = "^[1-9][0-9]*\\.[0-9]+$|^[1-9][0-9]*$|^0+\\.[0-9]+$";
		char c = s.charAt(0);
		boolean bool;
		if (c == '+' | c == '-') {
			bool = s.substring(1).matches(regex);
		} else {
			bool = s.matches(regex);
		}
		if (bool) {
			return 1;
		} else {
			return 0;
		}
	}

	public static String removeZero(String data) {
		if (!isNumber(data)) {
			return data;
		}
		float tmp = Float.parseFloat(data);
		data = String.valueOf(tmp);
		return data;
	}

	public static StringBuffer sql_check(StringBuffer sql) {
		String sqlstr = sql.toString();
		String[] inj_stra = { "update ", "delete ", "exec ", "master",
				"truncate ", "declare ", ";" };
		for (int i = 0; i < inj_stra.length; i++) {
			if (sqlstr.toLowerCase().indexOf(inj_stra[i]) >= 0) {
				sqlstr = sqlstr.replaceAll("(?i)" + inj_stra[i], "");
			}
		}
		StringBuffer sb = new StringBuffer(sqlstr);
		return sb;
	}

	

	public static String MD5(String sourceStr) {
		String result = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(sourceStr.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			result = buf.toString();
		} catch (NoSuchAlgorithmException e) {
			System.out.println(e);
		}
		return result;
	}

	public static byte[] hexStringToByte(String hex) {
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
		}
		return result;
	}

	private static int toByte(char c) {
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}

	public static int[] hexString2Byte(String src) {
		int m = 0, n = 0;
		int l = src.length() / 2;
		// System.out.println(l);
		int[] ret = new int[l];
		for (int i = 0; i < l; i++) {
			m = i * 2 + 1;
			n = m + 1;
			// 16进制转10进制，并且无符号byte 转有符号byte
			String str = "0x" + src.substring(i * 2, m) + src.substring(m, n);
			int temp = Integer.decode(str);
			ret[i] = temp;
		}
		return ret;
	}

	public static String getMiCmd(String key, String dara) {
		String result = "";
		try {
			if (key == null || key.equals("") || dara == null
					|| dara.equals("")) {
				return dara;
			}
			int l1 = key.length();
			int l2 = dara.length();
			if (l1 % 2 != 0) {
				return dara;
			}

			if (l2 % 2 != 0) {
				return dara;
			}

			if (l1 < l2) {
				for (int i = 0; i < l2 - l1; i++) {
					key = "F" + key;

				}
			}

			if (l1 > l2) {
				key = key.substring(l1 - l2, key.length());
			}

			int[] keylist = hexString2Byte(key);
			int[] daralist = hexString2Byte(dara);

			for (int i = 0; i < keylist.length; i++) {
				keylist[i] = keylist[i] ^ daralist[i];
				result = result + String.format("%02X", keylist[i]);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static char ascii2Char(int ASCII) {
		return (char) ASCII;
	}

	public static String ascii2String(String ASCIIs) {
		StringBuffer sb = new StringBuffer();
		try {
			sb.append((char) ascii2Char(Integer.parseInt(ASCIIs, 16)));
			String s = sb.toString();
			String ns = new String(s.getBytes("GBK"), "unicode");
		} catch (Exception e) {
			// TODO: handle exception
		}

		return sb.toString();
	}




	public static boolean isPicture(String pInput) {

		String[] strs = { "bmp", "png", "jpg", "jpeg", "gif" };
		// 获得文件后缀名
		String tmpName = pInput.substring(pInput.lastIndexOf(".") + 1,
				pInput.length());

		for (int i = 0; i < strs.length; i++) {
			if (strs[i].equals(tmpName.toLowerCase()))
				return true;
		}

		return false;
	}
	
	public static DataReq getParam(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) throws Exception {
		DataReq req = null;
		try {
			String param = request.getParameter("param");
			String ip = DBUtils.getIpAddress(request);
			String path = request.getRequestURI(); 
			StringBuffer sb = new StringBuffer() ;
			sb.append(ip).append(" ").append(path).append("  ").append(param) ;
			DBUtils.printLog(sb.toString());

			if (param == null || param.equals("")) {
				try {
					ServletInputStream in = request.getInputStream();
					param = inputStreamToString(in);
					// System.out.println(param);
				} catch (Exception e) {
					param = null;
				}
			}
			req = (DataReq) JsonUtil.getObjFromStr(param, DataReq.class);
		} catch (Exception e) {
		}

		if (req == null) {
			req = new DataReq();
		}
		return req;
	}
	
	public static String inputStreamToString(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] arr = new byte[1024];
		int len = -1;
		while ((len = is.read(arr)) != -1) {
			baos.write(arr, 0, len);
		}
		byte[] b = baos.toByteArray();
		String result = new String(b, "utf-8");// result结果显示正常：含中文无乱码
		return result;
	}
	
	public static DataRes setRemoteVisit(HttpServletRequest request,
			HttpServletResponse response,boolean useKey) {
		DataReq req=new DataReq();
		DataRes res = new DataRes();
		res.setRetCode(0);
		res.setRetMessage("OK");
		
		// 支持跨域访问************************************************************
		if (response == null) {
			return res;
		}
		response.setHeader("Access-Control-Allow-Origin",request.getHeader("origin"));
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Headers", "key");
		response.setHeader("Access-Control-Allow-Methods",
				"POST, GET, OPTIONS,DELETE,PUT");

		String token = request.getHeader("key");
		req.setKey(token);
		String method = request.getMethod();
		if (method.equals("OPTIONS")) {
			response.setStatus(200);
		}
		String pageid = request.getParameter("pageid");
		String pageSize =request.getParameter("pagesize");
		// pageId
		if (pageid == null || "".equals(pageid)) {
			pageid = request.getParameter("pageId");
		}
		if (pageSize == null || "".equals(pageSize)) {
			pageSize = request.getParameter("pageSize");
		}

		if(pageid!=null && !pageid.equals("")){
			req.setPageid(Integer.parseInt(pageid));
		} else {
			req.setPageid(1);
		}
		if(pageSize!=null && !pageSize.equals("")){
			req.setPagesize(Integer.parseInt(pageSize));
		}
		HashMap<String, Object> reqData = new HashMap<String, Object>();
		Enumeration<String> paramNames = request.getParameterNames();
		boolean isParam = false ;
		while(paramNames.hasMoreElements()){
		    String key=paramNames.nextElement().toString();
		    String[] value=request.getParameterValues(key) ;
		    if(value.length==1){
		    	reqData.put(key, value[0]);
		    }else{
		    	reqData.put(key, value);
		    }
		    isParam = true ;
		}
		if (!isParam) {
			String json = JSONObject.toJSONString(request.getParameterMap())
					.replaceAll("\\[\"", "\"")
					.replaceAll("\"\\]", "\"");
			reqData.putAll(JSONObject.parseObject(json));
			if (ObjectUtil.isNotEmpty(JSON.parseObject(JSON.toJSONString(reqData)))) {
				isParam = true;
			}
		}
		
		if(!isParam) {
			try {
				String json = readRaw(request.getInputStream()) ;
				if(!StringUtils.isEmpty(json)) {
					JSONObject jsonObject = JSONObject.parseObject(json);
					reqData.putAll(jsonObject);
				}
			} catch (IOException e) {
		        e.printStackTrace();
			}
		}
		
		//封装参数
		if (useKey) {		
			String value = req.getAppkey();
			if (value == null || value.equals("")) {
				value = req.getKey();
			}
			if (value == null || value.equals("")) {
				value = request.getHeader("key");
			}
			if (value == null || value.equals("")) {
				value = (String) reqData.get("key");
			}
			if (value == null || value.equals("")) {
				value = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJpc0F1dGhvclJvbGVcIjpcIjFcIixcInJvbGVOYW1lXCI6XCJSRUfms6jlhozor5XnlKjotKblj7dcIixcImNvbXBhbnlOYW1lXCI6XCLmsrPljZfmlrDog73mupDmvJTnpLrkvIHkuJpcIixcImNvbXBhbnlUeXBlXCI6XCIwMlwiLFwiY29tcGFueVR5cGVOYW1lXCI6XCLku6PnkIbllYZcIixcImlzQ2VydFwiOjAsXCJpZFwiOjY0OSxcInV1aWRcIjpcImIxMjlmMjQ5LWY0ZGUtNDFlNS1iZjU0LWYxM2RlYWNlYjAyY1wiLFwidXNlcm5hbWVcIjpcIjEzNTExMDA0Mjg2XCIsXCJwYXNzd29yZFwiOlwiMTIzNDU2XCIsXCJzZXhcIjpcIjJcIixcIm5pY2tOYW1lXCI6XCLmsrPljZfmlrDog73mupDmvJTnpLrkvIHkuJpcIixcInJvbGVfaWRcIjpcIjQxOTE5MGE0LTFhNmYtNDJiOS1iNGYxLTI1NDIyNGMxNWFkN1wiLFwiYXJlYWNvZGVcIjpcIlwiLFwiY29tcGFueUlkXCI6XCIwMDAwMDAzMFwiLFwiZGVwYXJ0bWVudElkXCI6XCIwMDAwMDAzMEQwMDJcIixcInBob25lXCI6XCIxMzUxMTAwNDI4NlwiLFwibG9uZ2l0dWRlXCI6MTE2LjQxNjI3MyxcImxhdGl0dWRlXCI6NDAuMDAzMjE5LFwiY3JlYXRlVWlkXCI6MCxcImNyZWF0ZVRpbWVcIjpcIk1hciA4LCAyMDIzIDM6NDk6MTUgUE1cIixcIm1vZGlmeVVpZFwiOjAsXCJtb2RpZnlUaW1lXCI6XCJNYXIgMjEsIDIwMjMgMjoyMjoyMyBQTVwiLFwic2ZzY1wiOjAsXCJpc09ubGluZVJlZ1wiOjEsXCJwaWNcIjpcIlwifSIsImlzcyI6ImFkbWludXNlciIsImV4cCI6MTcxMDk4NjU5OCwiaWF0IjoxNjc5NDUwNTk4LCJqdGkiOiIxMzUxMTAwNDI4NiJ9.7K6MFbvE75P3EaAI7lfi26TGKMb1UvzsiKkEqLjikaA";
			}
			if (value != null && !value.equals("")) {
				try {
					JwtUtil util = new JwtUtil();
					Claims c = util.parseJWT(value);// 注意：如果jwt已经过期了，这里会抛出jwt过期异常。
					String json = c.getSubject();
					UserInfo uinfo = (UserInfo) JsonUtil.getObjFromStr(
							json, UserInfo.class);
					if(uinfo.getCompanyId()==null) uinfo.setCompanyId("");
					if(uinfo.getAreacode()==null) uinfo.setAreacode("");
					uinfo.setProjectIds("");
					req.setUinfo(uinfo);
					res.setRetCode(0);
					res.setRetMessage("OK");
				} catch (Exception e) {
					res.setRetCode(999);
					res.setRetMessage("用户已过期!");
					return res;
				}
			} else {
				res.setRetCode(9);
				res.setRetMessage("用户验证失败!");
				return res;
			}
		}
		
		//保存访问日志
		
		String uri = request.getRequestURI() ;
		String param  = JsonUtil.getStriFromObj(reqData) ;
		String userName = "" ;
		String nickName = "" ;
		String id = "0" ;
		if(req.getUinfo()!=null) {
			userName = req.getUinfo().getUsername() ;
			nickName = req.getUinfo().getNickName() ;
			id = req.getUinfo().getId() ;
		}else {
			userName = (String) reqData.get("username") ;
		}
		String ip = getIpAddress(request) ;	
		
		// logDB( uri, param, userName, nickName, id,ip) ;
		
		String path = request.getRequestURI(); 
		StringBuffer sb = new StringBuffer() ;
		
		String userStr = "" ;
		if(req.getUinfo()!=null){
			userStr = req.getUinfo().getId()+" "+req.getUinfo().getUsername() ;
		}
		
		sb.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date())).append(": ").append("来自：").append(ip).append(" ").append(path).append("  ").append(userStr).append(" ").append(JsonUtil.getStriFromObj(reqData)) ;
		// System.out.println(sb);
		reqData.put("remoteIp", ip) ;
        req.setReqData(reqData) ;
        res.setReq(req) ;
        return res;
	}
	
	public static String readRaw(InputStream inputStream) {
		 
	    String result = "";
	    try {
	        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
	        byte[] buffer = new byte[1024];
	 
	        int len;
	        while ((len = inputStream.read(buffer)) != -1) {
	            outSteam.write(buffer, 0, len);
	        }
	 
	        outSteam.close();
	        inputStream.close();
	 
	        result = new String(outSteam.toByteArray(), "UTF-8");
	 
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	 
	    return result;
	}
	
	public static void logDB(String uri,String param,String userName,String nickName,String id,String ip){
		PreparedStatement ps = null;
		 Connection connTmp = null ;
		 try {
			 String remark =  nickName ;
			 connTmp = DBUtils.getJNDIDBConn() ;
			 String sql = "INSERT INTO `nes_agent`.`t_logs`(`uid`, `yhbs`, `yhmk`, `remark`, `sqllog`,`ip`) VALUES (?,?,?,(select name from  t_modelname where uri=? limit 1),?,?)" ;
			 ps = connTmp.prepareStatement(sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_UPDATABLE);
			 ps.setObject(1, id);
			 ps.setObject(2, userName+"-"+remark);
			 ps.setObject(3, uri);
			 ps.setObject(4, uri);
			 ps.setObject(5, param);
			 ps.setObject(6, ip);
			 ps.execute();
			 connTmp.commit();
		}catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				connTmp.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} 
	}

	
	public static void toJson(HttpServletResponse response, String data)
			throws Exception {
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.write(data);
		// System.out.println(data);
		out.flush();
		out.close();
	}
	
	public static String changeStreamToString(InputStream in) {
		StringBuffer sb = new StringBuffer();
		String readIn = null;
		try {
			BufferedReader re = new BufferedReader(new InputStreamReader(in,
					"UTF-8"));
			while ((readIn = re.readLine()) != null) {
				sb.append(readIn);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	
	public static int getValue(Connection conn,String sql) throws SQLException, IOException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		ps = conn.prepareStatement(sql,
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
		int value = 0;
		rs = ps.executeQuery();
		if (rs.next()) {
			value = rs.getInt(1);
		} else {
			throw new SQLException();
		}
		rs.close();
		ps.close();
		return value ;
	}
	
	public static String getKey(Connection conn,int keyIdx,int jb) throws SQLException, IOException {
		String key = "";
		StringBuffer sb = new StringBuffer();
		switch (keyIdx) {
		case 1: //获取类别代码
			sb.append("select f_nextval('category").append(jb).append("') ");
			int value = getValue(conn,sb.toString());
			int len = jb==1? 2:4 ;
			key = String.format("%0" + len + "d", value) ;
			break;
		case 2: //获取订单编号
			sb.append("select f_nextval('order").append(jb).append("') ");
			value = getValue(conn,sb.toString());
			key = String.format("%08d", value) ;
			break;	
		default:
			break;
		}
		return key;
	}
	//修改null值为“-”
	public static List<Map<String, Object>> getList(List<Map<String, Object>> list){
		for (Map<String, Object> map : list) {
			  for (Map.Entry<String, Object> m : map.entrySet()) {
			         if(null==m.getValue() || m.getValue().equals("null")){
			        	 map.put(m.getKey(), "-");
			         }
			    }
		}
		return list;
	}
	
	public static String getDjbh( String p_gsdm, String p_djlx)
			throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		StringBuffer sb = new StringBuffer();
		String csz = "";
		Connection conn = null ;
		try {
			if(Globals.IS_DEBUG) {
				conn = getJdbcForDB();
			}else {
				conn = getJNDIDBConn() ;
			}
			
			sb.delete(0, sb.length());
			sb.append(" select f_get_djbh('").append(p_gsdm).append("','")
					.append(p_djlx).append("') from dual ");
			ps = conn
					.prepareStatement(sb.toString(),
							ResultSet.TYPE_SCROLL_SENSITIVE,
							ResultSet.CONCUR_READ_ONLY);
			rs = ps.executeQuery();
			if (rs.next()) {
				csz = rs.getString(1);
			}
			conn.commit() ;
		}catch (Exception e) {
			conn.rollback() ;
		} finally {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
			if (conn != null)
				conn.close();
		}
		return csz;
	}
	
	public static Connection getJNDIDBConn() {
	Connection conn = null;
	try {
		Context initContext = new InitialContext();
		Context envContext = (Context) initContext.lookup("java:/comp/env");
		String jndi = "jdbc/AgentPlatform";
		DataSource ds = (DataSource) envContext.lookup(jndi);
		if (ds != null) {
			try {
				conn = ds.getConnection();
				conn.setAutoCommit(false);
				// System.err.println("JNDI 获取成功!");
			} catch (SQLException e) {
				try {
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					PrintWriter pw = new PrintWriter(out);
					e.printStackTrace(pw);
					pw.flush();
					System.err.println("JNDI 获取失败! 错误信息：" + new String(out.toByteArray()));
				} catch (Exception e1) {
					System.out.println("JNDI 获取失败! 2");
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		System.err.println("JNDI 获取失败!");
	}
	return conn;
}
	
	public static Connection getJdbcForDB() {
		return getJNDIDBConn();
//		Connection conn = null;
//		String url = "jdbc:mysql://rm-2ze3340731300n995no.mysql.rds.aliyuncs.com:3306/nes_agent?characterEncoding=utf-8" ;
//		String user = "ctcetest";
//		String password = "NES@ctceZO1B3";
//		try {
//			Class.forName("com.mysql.jdbc.Driver").newInstance();
//		} catch (InstantiationException e) {
//			e.printStackTrace();
//		} catch (IllegalAccessException e) {
//			e.printStackTrace();
//		} catch (ClassNotFoundException e) {
//			e.printStackTrace();
//		}
//		try {
//			conn = DriverManager.getConnection(url, user, password);
//			conn.setAutoCommit(false);
//		} catch (SQLException e1) {
//			e1.printStackTrace();
//		}
//		return conn;
	}	
	
	public static Connection getJdbcForOpe() {
		return getDBConn_Ope();
//		Connection conn = null;
//		String url = "jdbc:mysql://rm-2ze3340731300n995.mysql.rds.aliyuncs.com:3306/nes_ope_prod?characterEncoding=utf-8" ;
//		String user = "nes_ope_prod";
//		String password = "Db_opew0#M";
//		try {
//			Class.forName("com.mysql.jdbc.Driver").newInstance();
//		} catch (InstantiationException e) {
//			e.printStackTrace();
//		} catch (IllegalAccessException e) {
//			e.printStackTrace();
//		} catch (ClassNotFoundException e) {
//			e.printStackTrace();
//		}
//		try {
//			conn = DriverManager.getConnection(url, user, password);
//			conn.setAutoCommit(false);
//		} catch (SQLException e1) {
//			e1.printStackTrace();
//		}
//		return conn;
	}	
	
	
	
	public PageData getOss_Sign(DataReq req){
		PageData res = new PageData();
		try{
			String dir = (String) req.getReqData().get("g_osspath");
			
			if(StringUtils.isEmpty(dir)){
				res.setRetCode(0);
				res.setRetMessage("文件上传路径为空");
				return res;
			}
			
			String host = "http://" + Globals.bucketName + "."+ Globals.endpoint_nohttp;
			OSSClient client = new OSSClient(Globals.endpoint, Globals.accessKeyId,
					Globals.accessKeySecret);
			
			long expireTime = 30;
			long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
			Date expiration = new Date(expireEndTime);
			PolicyConditions policyConds = new PolicyConditions();
			policyConds.addConditionItem(
					PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
			policyConds.addConditionItem(MatchMode.StartWith,
					PolicyConditions.COND_KEY, dir);
			
			String postPolicy = client.generatePostPolicy(expiration,
					policyConds);
			
			byte[] binaryData = postPolicy.getBytes("utf-8");
			String encodedPolicy = BinaryUtil.toBase64String(binaryData);
			String postSignature = client.calculatePostSignature(postPolicy);
			
			Map<String, String> respMap = new LinkedHashMap<String, String>();
			respMap.put("accessid", Globals.accessKeyId);
			respMap.put("policy", encodedPolicy);
			respMap.put("signature", postSignature);
			// respMap.put("expire", formatISO8601Date(expiration));
			respMap.put("dir", dir);
			respMap.put("host", host);
			respMap.put("expire", String.valueOf(expireEndTime / 1000));
			res.setExtData(respMap);
			res.setRetCode(0);
			res.setRetMessage("OK");
			//UserLogic.SaveSyslog(req.getUinfo().getUserid(), "查询q", "查询成功", "systemset/getOss_Sign", Globals.LOG_TYPE4, conn);
		}catch(Exception e){
			e.printStackTrace();
			res.setRetCode(0);
			res.setRetMessage("ERROR");
		}
		return res;
	}
	
    /*
    public static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn,
                                            String roleSessionName, String policy, ProtocolType protocolType, long durationSeconds) throws ClientException, ServerException, com.aliyuncs.exceptions.ClientException
    {
    	String REGION_CN_HANGZHOU = "cn-beijing";
        String STS_API_VERSION = "2015-04-01";
        accessKeyId = "LTAI0dNVUDWc3HYn" ;
        accessKeySecret ="hACWMyy1VxN1htWD9Ud3QGUAezuHMf" ;
        roleArn = "acs:ram::20847759:role/aliyuncasdefaultrole" ;
        roleSessionName = "alice-001" ;
        policy = "{\"Statement\":[{\"Action\":[\"oss:*\"],\"Effect\":\"Allow\",\"Resource\":[\"acs:oss:*:*:*\"]}],\"Version\":\"1\"}" ;
        protocolType = ProtocolType.HTTPS;
        durationSeconds = 900 ;
        try {
            // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
            IClientProfile profile = DefaultProfile.getProfile(REGION_CN_HANGZHOU, accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);

            // 创建一个 AssumeRoleRequest 并设置请求参数
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setVersion(STS_API_VERSION);
            request.setMethod(MethodType.POST);
            request.setProtocol(protocolType);

            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy);
            request.setDurationSeconds(durationSeconds);

            // 发起请求，并得到response
            final AssumeRoleResponse response = client.getAcsResponse(request);

            return response;
        } catch (ClientException e) {
            throw e;
        }
    }
    */
	
	public static Connection getDBConn_Ope() {
	Connection conn = null;
	try {
		Context initContext = new InitialContext();
		Context envContext = (Context) initContext.lookup("java:/comp/env");
		String jndi = "jdbc/nes_ope_prod";
		DataSource ds = (DataSource) envContext.lookup(jndi);
		if (ds != null) {
			try {
				conn = ds.getConnection();
				conn.setAutoCommit(false);
				// System.err.println("JNDI 获取成功!");
			} catch (SQLException e) {
				try {
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					PrintWriter pw = new PrintWriter(out);
					e.printStackTrace(pw);
					pw.flush();
					System.err.println("JNDI 获取失败! 错误信息：" + new String(out.toByteArray()));
				} catch (Exception e1) {
					System.out.println("JNDI 获取失败! 2");
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		System.err.println("JNDI 获取失败!");
	}
	return conn;
}
	
	
	public static Connection getJNDIclikchouse() {
		Connection conn = null;
		try {
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");
			String jndi = "jdbc/clickhouse";
			DataSource ds = (DataSource) envContext.lookup(jndi);
			if (ds != null) {
				try {
					conn = ds.getConnection();
					conn.setAutoCommit(false);
					// System.err.println("JNDI 获取成功!");
				} catch (SQLException e) {
					try {
						ByteArrayOutputStream out = new ByteArrayOutputStream();
						PrintWriter pw = new PrintWriter(out);
						e.printStackTrace(pw);
						pw.flush();
						System.err.println("JNDI 获取失败! 错误信息：" + new String(out.toByteArray()));
					} catch (Exception e1) {
						System.out.println("JNDI 获取失败! 2");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("JNDI 获取失败!");
		}
		return conn;
	}
	
	
	public static Connection getDBConn_Weather() {
	Connection conn = null;
	try {
		Context initContext = new InitialContext();
		Context envContext = (Context) initContext.lookup("java:/comp/env");
		String jndi = "jdbc/weather";
		DataSource ds = (DataSource) envContext.lookup(jndi);
		if (ds != null) {
			try {
				conn = ds.getConnection();
				conn.setAutoCommit(false);
				// System.err.println("JNDI 获取成功!");
			} catch (SQLException e) {
				try {
					ByteArrayOutputStream out = new ByteArrayOutputStream();
					PrintWriter pw = new PrintWriter(out);
					e.printStackTrace(pw);
					pw.flush();
					System.err.println("JNDI 获取失败! 错误信息：" + new String(out.toByteArray()));
				} catch (Exception e1) {
					System.out.println("JNDI 获取失败! 2");
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		System.err.println("JNDI 获取失败!");
	}
	return conn;
}
	
    public static Date getLastDayOfMonth(String dateStr) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date date = sdf.parse(dateStr);
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        ca.set(Calendar.DAY_OF_MONTH, 1);
        ca.add(Calendar.MONTH, 1);
        ca.add(Calendar.DAY_OF_MONTH, -1);
        return ca.getTime();
    }
    
    private static double rad(double d){
    return d * Math.PI / 180.0;
    }
    
    public static double GetDistance(double lon1,double lat1,double lon2, double lat2) {
    	double EARTH_RADIUS = 6371000;//赤道半径(单位m)
    	double radLat1 = rad(lat1);
    	double radLat2 = rad(lat2);
    	double a = radLat1 - radLat2;
    	double b = rad(lon1) - rad(lon2);
    	double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    	s = s * EARTH_RADIUS;
    	s = Math.round(s * 10000) / 10000;
    	return s;

    }
    
    public static InputStream getHttpsFile(String fileUrl) throws NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyManagementException {
        // 创建SSLContext对象，使用指定的信任管理器初始化
        if (fileUrl.contains("https:")) {//https
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(fileUrl);
            HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
            httpsConn.setSSLSocketFactory(ssf);
            httpsConn.setDoInput(true);
            httpsConn.setDoOutput(true);
            return httpsConn.getInputStream();
        } else {//http
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10 * 1000);
            return connection.getInputStream();
        }
    }
    
    public static String getBase64(String url) {
        String result = "";
        //转成Base64
        InputStream httpsFile = null;
        try {
            httpsFile = getHttpsFile(url);
            byte[] bytes = IOUtils.toByteArray(httpsFile);
            result = DatatypeConverter.printBase64Binary(bytes);
            //result = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    //链接url下载图片
    public static void downloadPicture(String urlList,String imageName) {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static String getNumbers(String content) {  
        Pattern pattern = Pattern.compile("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])");  
        Matcher matcher = pattern.matcher(content);  
        while (matcher.find()) {  
            return matcher.group(0);  
        }  
        return "";  
    }  
    
    public static void main(String[] args) {
    	System.out.println(getNumbers("红包0.05元"));
	}
    
	public static PageData checkPower(Connection conn,DataReq req,String mkdm)
			throws SQLException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		StringBuffer sb = new StringBuffer();
		PageData res = new PageData();
		res.setRetCode(9);
		res.setRetMessage("没有操作权限！");
		try {
			String userName = req.getUinfo().getUsername() ;
			sb.delete(0, sb.length());
			sb.append(" SELECT count(1) cnt from t_user   a  INNER JOIN t_role_model c on a.role_id=c.role_id where a.username=? and c.model_id=? and c.isWrite = 1 ");
			ps = conn
					.prepareStatement(sb.toString(),
							ResultSet.TYPE_SCROLL_SENSITIVE,
							ResultSet.CONCUR_READ_ONLY);
			ps.setString(1, userName);
			ps.setString(2, mkdm);
			rs = ps.executeQuery();
			int cnt = 0 ;
			if (rs.next()) {
				cnt = rs.getInt("cnt") ;
			}
			if (cnt>0) {
				res.setRetCode(0);
				res.setRetMessage("OK");
				return res ;
			}
		} finally {
			if (rs != null)
				rs.close();
			if (ps != null)
				ps.close();
		}
		return  res ;
	}
    		
    		
}